package my.mall.config;

import my.mall.config.auth.LoginUserHandlerMethodArgumentResolver;
import my.mall.config.auth.UserAuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author fengbo
 * @version 1.0.0
 * @date 2018/11/22 16:26
 * @since JDK 1.8
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private UserAuthInterceptor userAuthInterceptor;
    @Autowired
    private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userAuthInterceptor)
                .excludePathPatterns("/login")
                .addPathPatterns("/**")
        ;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 允许跨域的域名，可以用*表示允许任何域名使用
                .allowedOrigins("*")
                // 允许任何方法（post、get等）
                .allowedMethods("*")
                // 允许任何请求头
                .allowedHeaders("*")
                // 带上cookie信息
                .allowCredentials(true)
                .exposedHeaders(HttpHeaders.SET_COOKIE)
                // maxAge(3600)表明在3600秒内，不需要再发送预检验请求，可以缓存该结果
                .maxAge(3600L);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
    }
}
